package com.zj.leetcode.medium.hash;

import java.util.HashMap;

/**
 * @program: algorithm
 * @description: 复制带随机指针的链表
 * 138 copy-list-with-random-pointer
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class CopyListWithRandomPointer {
    public static void main(String[] args) {
        Solution solution = new CopyListWithRandomPointer().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)
/*
// Definition for a Node.
class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
*/

    static class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

    class Solution {
        public Node copyRandomList(Node head) {
            Node order = head;
            Node last = null;
            Node newHead = null;

            HashMap<Node, Node> map = new HashMap<>();
            while (order != null) {
                Node node = new Node(order.val);
                if (last != null) {
                    last.next = node;
                } else {
                    newHead = node;
                }
                map.put(order, node);
                last = node;
                order = order.next;
            }


            order = head;
            Node newLast = newHead;
            while (order != null) {
                newLast.random = map.getOrDefault(order.random, null);
                newLast = newLast.next;
                order = order.next;
            }

            return newHead;

        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
